<?php

namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Loader;
use think\Request;

/**
 * 支付回调类
 **/
class Notify extends Controller
{
    /**
     * 回调处理：
     * 1：支付状态改为已支付
     * 2：修改优惠券为已使用状态
     * 3：分佣（分享官，城市合伙人）
     * */
    public function notice()
    {
        $data = json_decode(json_encode(simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        //业务处理代码请自行实现
        if ($data['result_code'] == 'SUCCESS' && $data['return_code'] == 'SUCCESS') {

            //接收附加数据
            $json_attach = $data['attach'];
            $attach_arr = json_decode($json_attach, true);

            //订单号
            $order_sn = $data['out_trade_no'];

            //查询订单支付状态；0：未支付；1：已支付
            $is_pay = Db::name('mini_order')->where(['pay_order_sn' => $order_sn])->value('is_pay');

            if ($is_pay == 0) {
                Db::startTrans();
                try {
                    $this->doGoodsOrder($order_sn);

                    echo 'SUCCESS';
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                }
            }

        }
    }

    /**
     * 商品订单支付成功处理业务逻辑
     * @param string $order_sn 支付订单号
     * */
    public function doGoodsOrder($order_sn)
    {
        $order_info = Db::name('mini_order')->where(['pay_order_sn' => $order_sn])->find();

        if (isset($order_info['is_pay']) && $order_info['is_pay'] == 0) {
            $order_id = $order_info['id'];

            $user_info = Db::table('fa_user')->field('id,money,coupon_count,user_type')->where('id', $order_info['user_id'])->find();

            $time = time();

            // 修改订单支付状态
            $update_order_data = [
                'is_pay' => 1,
                'status' => 1,
                'pay_time' => $time,
                'update_time' => $time
            ];
            Db::name('mini_order')->where(['id' => $order_id])->update($update_order_data);

            if ($order_info['pay_type'] == 2) {
                // 减少账户余额 && 减少抵扣券数量 && 赠送5张抵扣券
                $money = $user_info['money'] - $order_info['pay_price'];
                // 回调完成之后，剩余的抵扣券数量
                $send_coupon_count = $order_info['send_coupon_count'];
                $coupon_count = $user_info['coupon_count'] - $order_info['use_coupon_count'] + $send_coupon_count;

                $user_data = [
                    'money' => $money,
                    'coupon_count' => $coupon_count,
                ];
                Db::table('fa_user')->where('id', $order_info['user_id'])->update($user_data);

                // 生成账号余额消费记录
                $money_log_data = [
                    'user_id' => $order_info['user_id'],
                    'money' => $order_info['pay_price'],
                    'before' => $user_info['money'],
                    'after' => $money,
                    'type' => 1,
                    'remark' => '商品订单支付',
                    'create_time' => $time,
                    'link_id' => $order_info['id'],
                    'link_table' => 'fa_mini_order',
                    'from' => 2
                ];
                Db::name('mini_user_money_log')->insert($money_log_data);
            }

            $coupon_log = [];
            if ($order_info['use_coupon_count'] > 0) {
                // 生成抵扣券使用记录
                $coupon_log[] = [
                    'user_id' => $order_info['user_id'],
                    'coupon_count' => $order_info['use_coupon_count'],
                    'before' => $user_info['coupon_count'],
                    'after' => $user_info['coupon_count'] - $order_info['use_coupon_count'],
                    'type' => 1,
                    'remark' => '商品订单抵扣',
                    'create_time' => $time,
                    'link_id' => $order_info['id'],
                    'link_table' => 'fa_mini_order'
                ];
            }
            // 生成赠送抵扣券记录
            if($send_coupon_count > 0){
                $coupon_log[] = [
                    'user_id' => $order_info['user_id'],
                    'coupon_count' => $order_info['use_coupon_count'],
                    'before' => $user_info['coupon_count'] - $order_info['use_coupon_count'],
                    'after' => $coupon_count,
                    'type' => 2,
                    'remark' => '购买商品赠送',
                    'create_time' => $time,
                    'link_id' => $order_info['id'],
                    'link_table' => 'fa_mini_order'
                ];
            }
            if($coupon_log) Db::name('mini_user_coupon_log')->insertAll($coupon_log);

            // 升级VIP
            if ($user_info['user_type'] == 1 && $order_info['up_vip'] == 1) Db::table('fa_user')->where('id', $order_info['user_id'])->setField('user_type', 2);

            // TODO：分销


            $vice_order_list = Db::name('mini_vice_order')->where(['order_id' => $order_id])->select();
            if ($vice_order_list) {
                foreach ($vice_order_list as &$v) {
                    // 增加销量
                    Db::name('mini_goods')->where(['id' => $v['goods_id']])->setInc('sales_count', $v['count']);
                }
            }
        }
    }
}